package com.youyiwen.Controller;

import com.youyiwen.Bean.ImgInfo;
import com.youyiwen.Bean.Question;
import com.youyiwen.Bean.User;
import com.youyiwen.Mapper.QuestionMapper;
import com.youyiwen.Service.QuestionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * @Author: zhaoyang
 * @Date: 2021/03/16
 */
@Controller
public class PublishController {

    @Autowired
    private QuestionMapper questionMapper;

    @GetMapping("/publish")
    public String getPublish() {

        return "publish";
    }

    @PostMapping("/publish")
    public String postPublish(
            @RequestParam("title") String title,
            @RequestParam("description") String description,
            @RequestParam("tag") String tag,
            @RequestParam("questionID") String questionID,
            @RequestParam("simp_des") String simpDes,
            HttpSession session,
            Model model
    ) {
        User user = (User) session.getAttribute("loginUser");

        if (user == null) {
            model.addAttribute("msg", "请您登录后再进行发帖操作");
            return "login";
        }

        model.addAttribute("title", title);
        model.addAttribute("description", description);

        if (title == null || title == "" || description == null || description == "") {
            model.addAttribute("msg", "标题和内容都要补全才能找到答案哦！");
            return "publish";
        }


        Question question = questionMapper.getById(questionID);
        Long current = System.currentTimeMillis();
        if(simpDes.length()>80) simpDes = simpDes.substring(0,80) + "...";
        //首次发布
        if (question == null) {

            question = new Question();
            question.setUserName(user.getUserName());
            question.setTitle(title);
            question.setDescription(description);
            question.setTag(tag);
            question.setLikeCount(0);
            question.setViewCount(1);
            question.setCommentCount(0);
            question.setGmtCreate(current);
            question.setGmtModify(current);
            question.setLastReplyTime(current);
            question.setId(UUID.randomUUID().toString());
            question.setSimpDes(simpDes);
            System.out.println(simpDes);
            // insert
            questionMapper.insertQuestion(question);
            return "redirect:/communityCenter/all/last_reply_time";
        }
        questionMapper.updateQuestion(title,description,simpDes,current,questionID);
        return "redirect:/communityCenter/all/last_reply_time";
    }

    @GetMapping("/publish/{id}")
    public String edit(@PathVariable(name = "id") String id,
                       Model model){
        Question question = questionMapper.getById(id);
        if (question == null){
            return "redirect:/communityCenter/all/last_reply_time";
        }
        model.addAttribute("title",question.getTitle());
        model.addAttribute("description",question.getDescription());
        model.addAttribute("tag",question.getTag());
        model.addAttribute("questionID",question.getId());
        return "publish";
    }



    @PostMapping("/img/upload")
    @ResponseBody
    public ImgInfo setImgUrl(MultipartFile file, HttpServletRequest request)
            throws Exception {
        // Get the file and save it somewhere
        byte[] bytes = file.getBytes();
//        System.out.println(new String(bytes));
        String path = request.getServletContext().getRealPath("/pictures/");
        System.out.println("path:" + path);
        File imgFile = new File(path);
        if (!imgFile.exists()) {
            imgFile.mkdirs();
        }
        String fileName = System.currentTimeMillis() + file.getOriginalFilename() ;// 文件名称
//        服务器路径
//        System.out.println(path + fileName);
        try (FileOutputStream fos = new FileOutputStream(new File(path + fileName))) {
            int len = 0;
            fos.write(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        }

        String localPath = "D:/新建文件夹/springboot2/youyiwen1/src/main/resources/static/pictures";
        File dest = new File(localPath + "/" + fileName);
        if (!dest.getParentFile().exists()) { //判断文件父目录是否存在
            dest.getParentFile().mkdir();
        }try{
            file.transferTo(dest); //保存文件
        }catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String imgUrl = "http://localhost:8080/pictures/" + fileName;
        String[] values = { imgUrl };

        ImgInfo imgInfo = new ImgInfo();
        imgInfo.setError(0);
        imgInfo.setUrl(values);

//        System.out.println(imgInfo.toString());
        return imgInfo;
    }


}
